import numpy as np
from neuralnetwork import NeuralNetwork
import random
import matplotlib.pyplot as plt
# 切割数据集
def split_dataset(num=0.7,den=0.3):
    # 按照7：3比例进行切分，并分别保存
    f=open('all.csv','r')
    lines=f.readlines()
    random.shuffle(lines)
    f.close()
    size=len(lines)
    train_size=int(size*num)
    test_size=int(size-train_size)
    return lines[0:train_size],lines[train_size:]

if __name__=='__main__':
    # 每张图像1200像素，每个像素都是一个输入值
    input_nodes=1200
    # 共计62个输出值，因此分620个隐藏层
    hidden_nodes=620
    # 输出层节点数量，本例为判断62个数字
    output_nodes=62
    # 设置学习率为0.3
    learn_rate=0.1

    n=NeuralNetwork(input_nodes,hidden_nodes,output_nodes,learn_rate)

    train_dataset,test_dataset=split_dataset(num=0.9)
    print('训练集数量：',len(train_dataset),'测试集数量',len(test_dataset))

    chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
             'V', 'W', 'X', 'Y', 'Z',
             'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
             'v', 'w', 'x', 'y', 'z']

    # data_file=open('all.csv','r',encoding='utf-8')
    # data_list=data_file.readlines()
    # data_file.close()
    print("训练开始....修改训练次数可改变预测准确度")
    for i in range(5):
        print('第',i,'轮')
        # train_dataset, test_dataset = split_dataset()
        for line in train_dataset:
            arr=line.split(',')
            inputs=np.asfarray(arr[1:])/255*0.99+0.01
            targets=np.zeros(output_nodes)+0.01
            targets[chars.index(arr[0])]=0.99
            # print('arr is:',arr)
            # print('inputs is:',inputs)
            # print('targets is:',targets)
            #break
            n.train(inputs,targets)


    print("训练结束.....")
    print("测试开始......")
    cnt=0
    score=[]
    for record in test_dataset:
        #print("测试数据：",record)
        print('测试数据目标值：',record[0])
        arr=record.split(',')
        inputs=np.asfarray(arr[1:])
        image_array=inputs.reshape((40,30))
        # plt.imshow(image_array,cmap='Greys',interpolation='None')
        # plt.show()
        r=n.query(inputs)
        # for i in r:
        #     print('%.2f' % i)
        max=np.argmax(r)
        print('最大值：',r[max],'预测值：',chars[max])
        if chars[max]==record[0]:
            score.append(1)
        else:
            score.append(0)
        cnt+=1
        if cnt>=100:break
    print('score:',score)
    score_array=np.asarray(score)
    print("performance:",score_array.sum()/score_array.size)
    print("测试结束......")


